#include "../inc/uart.h"
#include <stdbool.h>
#include <avr/pgmspace.h>

//----------- CCITT ----------------//

unsigned char data_flash;

unsigned int addr_flash;

unsigned short crc;

void clear_crc16(void)
{
  crc = 0xFFFF;
}

void crc16_sum(unsigned char data)
{
  unsigned char i;
      crc ^= data++ << 8;
      for (i = 0; i < 8; i++)
      crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc << 1;

}

unsigned short crc16_package(void)
{
      clear_crc16();
      
      for (unsigned char i = 0; i<64; i++) crc16_sum(rec_buf[i]);

      return crc;      
}


bool crc16_code(void)   
{
    clear_crc16(); 
  
    for (addr_flash = 0x0000; addr_flash<0x17FE; addr_flash++)
    {
        data_flash = pgm_read_byte(addr_flash);
        crc16_sum(data_flash);
    }
    
   addr_flash = 0x17FF;
   data_flash = pgm_read_byte(addr_flash);
    
   unsigned short crc_temp = data_flash;
   crc_temp <<= 8;
     
   data_flash = pgm_read_byte(addr_flash);
   
   crc_temp += data_flash;
      
   if(crc == crc_temp) return true;
   else return false;
}
